//
//  YTHomeFollowController.m
//  yitaicaijing
//
//  Created by DIANGHONG on 2018/9/18.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "YTHomeFollowController.h"
#import "YTFollowAutherCell.h"
#import "YTHomeArticleCell.h"
#import "YTHomeFollowHeaderView.h"

#define kHomeFollowHeaderFrame CGRectMake(0, 0, kScreenWidth, 44);


NSString *kHomeFollowArticleCellID = @"kHomeFollowArticleCellID";
NSString *kHomeAuthorCellID = @"kHomeAuthorCellID";
@interface YTHomeFollowController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic ,assign)BOOL isLogin;

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic ,strong)YTFollowAuthorModel *authorModel;

@property(nonatomic ,strong)YTHomeMainModel *articleModel;

@property(nonatomic ,assign)BOOL isAuthorList;

@property(nonatomic ,strong)YTHomeFollowHeaderView *headerView;

@end

@implementation YTHomeFollowController

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        self.headerView = [YTHomeFollowHeaderView headerViewWithTip:nil];
        _tableView.tableHeaderView = self.headerView;
        
        
        // setRefresh
        YTRefreshHeader *header = [YTRefreshHeader headerWithRefreshingBlock:^{
            
            self.isLogin ? [self loadArticleListWithPullup:false] : [self loadAuthorListWithPullup:false];
        }];
        
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.isLogin ? [self loadArticleListWithPullup:YES] : [self loadAuthorListWithPullup:YES];
        }];
        
        
        [footer setTitle:@"没有更多了哦～" forState:MJRefreshStateNoMoreData];
        [footer setTitle:@"" forState:MJRefreshStateIdle];
        
        
        _tableView.backgroundColor = [UIColor colorWithHex:@"f1f2f2"];
        
        
        _tableView.mj_header = header;
        _tableView.mj_footer = footer;
        
        //_tableView.contentInset = UIEdgeInsetsZero;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _tableView.rowHeight = 110;
        // regist cell
        [_tableView registerNib:[UINib nibWithNibName:@"YTHomeArticleCell" bundle:nil]
         forCellReuseIdentifier:kHomeFollowArticleCellID];
        
        [_tableView registerNib:[UINib nibWithNibName:@"YTFollowAutherCell" bundle:nil]
         forCellReuseIdentifier:kHomeAuthorCellID];

        
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

- (BOOL)isLogin
{
    return YTNetworkManager.shareManager.account.auth;
}

- (void)setIsAuthorList:(BOOL)isAuthorList
{
    _isAuthorList = isAuthorList;
    self.headerView.tipStr = isAuthorList ? @"推荐关注以下优质作者" : nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    [self.view addSubview:self.tableView];

    self.tableView.frame = self.view.bounds;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.isLogin ? [self loadArticleListWithPullup:false] : [self loadAuthorListWithPullup:false];

}



#pragma mark； - 加载作者列表数据
- (void)loadAuthorListWithPullup:(BOOL)pullup
{
    int page = self.authorModel ? self.authorModel.page.intValue : 1;
    
    if (pullup) {
        page++;
        if (self.authorModel.list.count >= self.authorModel.total.intValue) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            return;
        }
    }else{
        page = 1;
    }
    
    [YTNetworkManager.shareManager requestFollowListWithIsAuthorList:YES
                                                               paged:page
                                                          completion:^(YTFollowAuthorModel *model, BOOL isSucc, NSString *error)
     {
         if (!isSucc) {
             [self.view showTipWithTipStr:error];
             pullup ? [self.tableView.mj_footer endRefreshing] : [self.tableView.mj_header endRefreshing];
             return ;
         }
         
         if (pullup) {
             self.authorModel.list = [self.authorModel.list arrayByAddingObjectsFromArray:model.list];
             [self.tableView.mj_footer endRefreshing];
             
         }else{
             self.authorModel = model;
             
             [self.tableView.mj_header endRefreshing];
             
             self.headerView.frame = kHomeFollowHeaderFrame

         }
         
         
         
         self.isAuthorList = YES;

         error ? nil : [self.tableView reloadData];
     }];
}

#pragma mark: - 加载关注作者发表文章
- (void)loadArticleListWithPullup:(BOOL)pullup
{
    if (pullup) {
        
        if (self.articleModel.list.count == self.articleModel.total.intValue) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            return;
        }
    }else{
        self.tableView.mj_footer.state = MJRefreshStateIdle;
    }
    
    NSLog(@"%@", self.articleModel.list.lastObject.post_date);
    [YTNetworkManager.shareManager requestFocusAuthorArticleWithPage_size:@"10"
                                                               menu_order:pullup ? self.articleModel.list.lastObject.menu_order : @"1"
                                                                  maxtime:nil
                                                                  mintime:pullup ? self.articleModel.list.lastObject.post_date : nil
                                                               completion:^(YTHomeMainModel *model, BOOL isSucc, NSString *error)
    {
        if (!isSucc) {
            [self.view showErrorWithTipStr:error];
            pullup ? [self.tableView.mj_footer endRefreshing] : [self.tableView.mj_header endRefreshing];
            
            return ;
        }
        
        // 下拉刷新
        if (!pullup) {
            self.articleModel = model;
            [self.tableView.mj_header endRefreshing];
            
            if (model.list.count > 0) {
                self.isAuthorList = false;
            }else{
                [self loadAuthorListWithPullup:false];
                
                (model.followNum.intValue > 0) ? [self.view showErrorWithTipStr:@"您关注的作者未发布过文章"] : nil;
            }
            self.headerView.frame = CGRectZero;
        }else{
            
            self.articleModel.list = [self.articleModel.list arrayByAddingObjectsFromArray:model.list];
            [self.tableView.mj_footer endRefreshing];
            
            self.isAuthorList = false;

        }
        
        
        [self.tableView reloadData];
    }];
}

#pragma mark: - table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.isAuthorList ? self.authorModel.list.count : self.articleModel.list.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = self.isAuthorList ? kHomeAuthorCellID : kHomeFollowArticleCellID;
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID
                                                            forIndexPath:indexPath];
    
    if (self.isAuthorList) {
        
        [(YTFollowAutherCell *)cell setIsAuthorList:YES];
        [(YTFollowAutherCell *)cell setModel:self.authorModel.list[indexPath.row]];
        
      
        [(YTFollowAutherCell *)cell setToFollowAuthorBlock:^(NSInteger idx) {
            
            if (idx == kShouldLoginCode) {
                YTLoginViewController *logVC = [[YTLoginViewController alloc] init];
                [self.navigationController pushViewController:logVC animated:true];
                return ;
            }
            
            [self loadArticleListWithPullup:false];
        }];
        
        
        [(YTFollowAutherCell *)cell setAuthorIconClickBlock:^(NSString *authorID) {
            
            YTAuthorInfoController *infoVC = [[YTAuthorInfoController alloc] init];
            infoVC.user_id = authorID;
            [self.navigationController pushViewController:infoVC animated:true];
        }];
        
    }else{
        [(YTHomeArticleCell *)cell setArticle:self.articleModel.list[indexPath.row]];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark: - table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.isAuthorList ? 74 : (iPhone5 ? 80 : 104);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isAuthorList) {
        return;
    }
    YTHomeArticle *article = self.articleModel.list[indexPath.row];
    
    YTHomeDetailController *detailVC = [[YTHomeDetailController alloc] init];
    detailVC.ID = article.ID;
    [self.navigationController pushViewController:detailVC animated:true];
}

@end
